package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novel/models"
)

type NovelController struct {
	beego.Controller
}
type JsonMsg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NovelController) Add() {
	name := c.GetString("name")
	author := c.GetString("author")
	img := c.GetString("img")
	cate := c.GetString("img")
	address := c.GetString("address")
	novel := models.Novel{
		Name:    name,
		Author:  author,
		Img:     img,
		Cate:    cate,
		Address: address,
	}
	err := models.DB.Create(&novel).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *NovelController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 3)
	name := c.GetString("name")
	var total int64
	query := models.DB.Model(&models.Novel{})
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	err := query.Count(&total).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "总数查询失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	var novel []models.Novel
	err = query.Offset((page - 1) * pageSize).Limit(pageSize).Find(&novel).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "分页失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		JsonData := make(map[string]interface{})
		JsonData["novel"] = novel
		JsonData["total"] = total
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "分页成功",
			Data: JsonData,
		}
		c.ServeJSON()
	}
}
func (c *NovelController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Novel{}, id).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
